
/**
* ErnieView.vue - 百度文心一言AI聊天页面
*/

<script setup>
import { defineOptions, ref, onMounted, onActivated, onDeactivated, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { ChatDotRound, ChatLineRound, Service, User, Position, Loading } from '@element-plus/icons-vue'
import ernieApi from '../services/baiduErnieApi.js'
import { useChatStore } from '../stores/chatStore'

defineOptions({
  name: 'ErnieView'
})

// 获取聊天记录store
const chatStore = useChatStore()

// 组件状态
const messages = ref([]) // 聊天消息历史
const inputMessage = ref('') // 用户输入
const loading = ref(false) // 加载状态
const messageContainerRef = ref(null) // 消息容器引用

// AI参数设置
const aiSettings = ref({
  temperature: 0.95,
  top_p: 0.8,
  penalty_score: 1,
  stream: false
})

// 添加延迟函数
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms))

// 组件被激活时触发
onActivated(() => {
  nextTick(() => {
    if (messageContainerRef.value) {
      messageContainerRef.value.scrollTop = messageContainerRef.value.scrollHeight
    }
  })
})

// 组件被停用时触发
onDeactivated(() => {
  // 可以在这里处理停用时的逻辑
})

/**
 * 发送消息到文心一言API
 * @param {string} content - 用户输入的消息内容
 */
const handleSendMessage = async (content) => {
  if (!content.trim() || loading.value) return

  try {
    loading.value = true
    await delay(100)

    // 添加用户消息到消息列表和store
    const userMessage = { role: 'user', content }
    messages.value.push(userMessage)
    chatStore.addErnieMessage(userMessage)

    // 发送消息到文心一言API
    const response = await ernieApi.chat(messages.value, {
      temperature: aiSettings.value.temperature,
      top_p: aiSettings.value.top_p,
      penalty_score: aiSettings.value.penalty_score
    })

    // 添加AI回复到消息列表和store
    if (response && response.result) {
      const aiMessage = { role: 'assistant', content: response.result }
      messages.value.push(aiMessage)
      chatStore.addErnieMessage(aiMessage)
    } else {
      console.error(response)
      throw new Error(  response?.error_msg||'无效的API响应')
    }

    // 清空输入框
    inputMessage.value = ''

    // 滚动到底部
    await nextTick()
    scrollToBottom()
  } catch (error) {
    console.error('Error:', error)
    
    // 显示错误提示
    ElMessage({
      message: error.message || '请求失败，请稍后重试',
      type: 'error',
      duration: 5000,
      showClose: true
    })
  } finally {
    loading.value = false
  }
}

/**
 * 处理键盘事件
 * @param {Event} event - 键盘事件对象
 */
const handleKeyPress = (event) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault()
    handleSendMessage(inputMessage.value)
  }
}

/**
 * 滚动消息容器到底部
 */
const scrollToBottom = () => {
  if (messageContainerRef.value) {
    messageContainerRef.value.scrollTop = messageContainerRef.value.scrollHeight
  }
}

// 组件挂载时初始化
onMounted(() => {
  if (messageContainerRef.value) {
    messageContainerRef.value.scrollTop = messageContainerRef.value.scrollHeight
  }
})

</script>

<template>
  <div class="ernie-view">
    <el-row justify="center" class="el-row">
      <el-col :span="24" class="center">
        <h1 class="text-center">百度文心一言 AI Chat</h1>
        <div class="chat-container">
          <!-- 消息列表 -->
          <div ref="messageContainerRef" class="message-container">
            <template v-if="messages.length === 0">
              <div class="welcome-message">
                <el-icon class="service-icon" style="height: 100%;">
                  <Service />
                </el-icon>
                <h2>欢迎使用百度文心一言AI助手</h2>
                <p>我是百度文心一言大模型4.0，可以帮您回答问题、编写代码、撰写文章等。</p>
                <p>请在下方输入你的问题，按Enter发送。</p>
              </div>
            </template>
            <template v-else>
              <div v-for="(message, index) in messages" :key="index"
                :class="['message', message.role === 'user' ? 'user-message' : 'ai-message']">
                <div class="message-avatar">
                  <el-icon :size="36">
                    <component :is="message.role === 'user' ? 'User' : message.role === 'assistant' ? 'Service' : null" />
                  </el-icon>
                </div>
                <div class="message-content">
                  <div class="message-text">{{ message.content }}</div>
                  <div class="message-time">{{ new Date().toLocaleTimeString() }}</div>
                </div>
              </div>
            </template>
          </div>

          <!-- 输入区域 -->
          <div class="input-container">
            <el-input v-model="inputMessage" type="textarea" :rows="3"
              :placeholder="loading ? '正在思考中...' : '输入消息，按Enter发送，Shift+Enter换行'" @keydown="handleKeyPress"
              :disabled="loading" resize="none">
              <template #prefix>
                <el-icon>
                  <ChatLineRound />
                </el-icon>
              </template>
            </el-input>
            <el-button type="primary" @click="handleSendMessage(inputMessage)" :loading="loading"
              :disabled="!inputMessage.trim() || loading">
              <el-icon v-if="!loading">
                <Position />
              </el-icon>
              <el-icon v-else>
                <Loading />
              </el-icon>
              <span>{{ loading ? '思考中...' : '发送' }}</span>
            </el-button>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<style lang="scss" scoped>
.ernie-view {
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
  background-color: #f5f7fa;

  .el-row {
    height: 100%;
  }

  .center {
    display: flex;
    flex-direction: column;
    height: 100%;
  }

  h1 {
    margin: 0 0 20px;
    color: #409eff;
    font-size: 24px;
  }

  .chat-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    background: white;
    border-radius: 8px;
    height: 95vh;
    max-height: calc(100% - 50px);
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    padding: 20px;
  }

  .message-container {
    flex: 1;
    overflow-y: auto;
    padding: 10px;
    margin-bottom: 20px;

    .welcome-message {
      text-align: center;
      padding: 40px 20px;

      .service-icon {
        font-size: 48px;
        color: #409eff;
        margin-bottom: 20px;
      }

      h2 {
        color: #303133;
        margin-bottom: 16px;
      }

      p {
        color: #606266;
        margin: 8px 0;
      }
    }

    .message {
      display: flex;
      margin-bottom: 20px;
      align-items: flex-start;

      &.user-message {
        flex-direction: row-reverse;

        .message-content {
          margin-right: 12px;
          margin-left: 0;
          background-color: #ecf5ff;
        }

        .message-avatar {
          color: #409eff;
        }
      }

      &.ai-message {
        .message-content {
          background-color: #f4f4f5;
        }

        .message-avatar {
          color: #909399;
        }
      }

      .message-avatar {
        flex-shrink: 0;
      }

      .message-content {
        max-width: 80%;
        margin-left: 12px;
        padding: 12px;
        border-radius: 8px;

        .message-text {
          font-size: 12px;
          line-height: 1.6;
          white-space: pre-wrap;
          word-break: break-word;
        }

        .message-time {
          font-size: 12px;
          color: #909399;
          margin-top: 4px;
        }
      }
    }
  }

  .input-container {
    display: flex;
    gap: 12px;
    padding-top: 20px;
    border-top: 1px solid #dcdfe6;

    .el-input {
      flex: 1;
    }

    .el-button {
      align-self: flex-end;
    }
  }
}
</style>